package frog.lazy.framework.http.deserializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import frog.lazy.framework.core.base.IBaseEnum;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class IBaseEnumDeserializer <T extends Enum<T> & IBaseEnum> extends JsonDeserializer<T>{

    private final Class<T> clz;

    private final T[] clzEnums;

    public IBaseEnumDeserializer(Class<T> clz) {
        this.clz = clz;
        this.clzEnums = clz.getEnumConstants();
    }

    @Override
    public T deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        int value = jsonParser.getValueAsInt();
        for (T clzEnum : clzEnums) {
            if (value == clzEnum.getValue()) {
                return clzEnum;
            }
        }
        return null;
    }
}
